package com.showtao.front.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.showtao.common.dto.ResultDto;
import com.showtao.common.dto.ResultDtoFactory;
import com.showtao.common.dto.widget.DataTablesResponseDto;
import com.showtao.common.util.JsonUtil;
import com.showtao.common.validation.ValidateException;
import com.showtao.front.domain.MobileOrder;
import com.showtao.front.domain.MobileUser;
import com.showtao.front.domain.Order;
import com.showtao.front.dto.upstream.MobileUserLoginDto;
import com.showtao.front.dto.upstream.OrderQueryRequestDto;
import com.showtao.front.dto.upstream.SMSSendingDto;
import com.showtao.front.dto.upstream.SMSValidatingDto;
import com.showtao.front.service.MobileUserService;
import com.showtao.front.service.OrderService;
import com.showtao.front.service.VehicleService;

@Controller
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private VehicleService vehicleService;
    @Autowired
    private MobileUserService mobileUserService;
    
    @RequestMapping(value = "/order/send_sms", method = RequestMethod.POST)
    @ResponseBody
    public ResultDto doSendSMS(@Valid @RequestBody SMSSendingDto dto,
            BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new ValidateException(result);
        }
        orderService.sendValidationCode(dto.getMobile());
        return ResultDtoFactory.toAck("短信验证码发送成功");
    }
    
    @RequestMapping(value = "/order/validate_sms", method = RequestMethod.POST)
    @ResponseBody
    public ResultDto doValidateSMS(@Valid @RequestBody SMSValidatingDto dto,
            BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new ValidateException(result);
        }
        orderService.validateCode(dto.getMobile(), dto.getCode());
        return ResultDtoFactory.toAck("短信验证成功");
    }
    
    @RequestMapping(value = "/orders", method = RequestMethod.POST)
    @ResponseBody
    public DataTablesResponseDto<Order> doSearchOrders(
            @Valid @RequestBody OrderQueryRequestDto requestDto,
            BindingResult result, HttpSession session) throws Exception {
        if (result.hasErrors()) {
            throw new ValidateException(result);
        }
        Pageable pageable = requestDto.toPagable();
        Page<Order> page = orderService.findOrdersByMobile(requestDto.getMobile(), pageable);
        DataTablesResponseDto<Order> responseDto = new DataTablesResponseDto<Order>();
        return responseDto.populateFromPage(page, requestDto.getDraw());
    }
    
    @RequestMapping(value = "order/login", method = RequestMethod.POST)
	@ResponseBody
	public ResultDto myOrderLogin(@Valid @RequestBody MobileUserLoginDto requestDto,
            BindingResult result, HttpSession session)
			throws Exception {
    	if (result.hasErrors()) {
            throw new ValidateException(result);
        }
		MobileUser mu=mobileUserService.getByMobile(requestDto.getMobile());
		if(mu != null){
			if(mu.getPassword() != null && mu.getPassword().equals(requestDto.getPwd())){
				session.setAttribute("mobileUser", mu);
			}else{
				return ResultDtoFactory.toNack("密码错误，请输入正确的密码！");
			}
		}else{
			return ResultDtoFactory.toNack("此账户不存在，请注册后再登录！");
		}
		if (result.hasErrors()) {
            throw new ValidateException(result);
        }
		return ResultDtoFactory.toAck("登录成功", mu.getMobile());
	}
    
    @RequestMapping(value = "order/logOut", method = RequestMethod.POST)
    @ResponseBody
	public ResultDto myOrderLogOut(Model model, HttpSession session) throws Exception {
		session.removeAttribute("mobileUser");
		return ResultDtoFactory.toAck("注销成功");
	}
    
    @RequestMapping(value = "/myorders", method = RequestMethod.POST)
    @ResponseBody
    public DataTablesResponseDto<MobileOrder> doSearchMyOrders(
            @Valid @RequestBody OrderQueryRequestDto requestDto,
            BindingResult result, HttpSession session) throws Exception {
        if (result.hasErrors()) {
            throw new ValidateException(result);
        }
        MobileUser mobileUser=(MobileUser)session.getAttribute("mobileUser");
        DataTablesResponseDto<MobileOrder> responseDto = new DataTablesResponseDto<MobileOrder>();
        if(mobileUser == null ){
        	responseDto.setData(new ArrayList<MobileOrder>());
        	return responseDto;
        }
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    	Date sDate=null;
    	Date eDate=null;
		if (StringUtils.isEmpty(requestDto.getStartDate())
				&& StringUtils.isEmpty(requestDto.getEndDate())) {
			eDate = new Date();
			Calendar c = Calendar.getInstance();
			c.add(Calendar.DAY_OF_MONTH, -10);
			c.set(Calendar.HOUR_OF_DAY, 0);
			c.set(Calendar.MINUTE, 0);
			c.set(Calendar.SECOND, 0);
			c.set(Calendar.MILLISECOND, 0);
			sDate = c.getTime();
		} else {
			if (StringUtils.isNotEmpty(requestDto.getStartDate())) {
				sDate = sdf.parse(requestDto.getStartDate());
			}
			if (StringUtils.isNotEmpty(requestDto.getEndDate())) {
				eDate = sdf.parse(requestDto.getEndDate());
			}
		}
        Pageable pageable = requestDto.toPagable();
        Page<MobileOrder> page = orderService.findMyOrdersPC(mobileUser.getMobile(), sDate, eDate , pageable);
        return responseDto.populateFromPage(page, requestDto.getDraw());
    }
    
    @RequestMapping(value = "order/exportMyOrder", method = RequestMethod.POST)
   	@ResponseBody
   	public void exportMyOrder(String startDate, String endDate, HttpSession session, HttpServletResponse response){
    	MobileUser mobileUser=(MobileUser)session.getAttribute("mobileUser");
		if(mobileUser!=null){
	    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	    	Date sDate=null;
	    	Date eDate=null;
	    	try {
	    		if((startDate==null  || startDate.length()==0)&& (endDate==null || endDate.length()==0)){
	    			eDate=new Date();
	    			Calendar c = Calendar.getInstance();
		    		c.add(Calendar.DAY_OF_MONTH, -10);
		    		c.set(Calendar.HOUR_OF_DAY, 0);
		    		c.set(Calendar.MINUTE, 0);
		    		c.set(Calendar.SECOND, 0);
		    		c.set(Calendar.MILLISECOND, 0);
		    		sDate=c.getTime();
	    		}else{
	    			if(startDate != null && startDate.length() > 0){
	    				sDate = sdf.parse(startDate);
	    	    	}
	    			if(endDate != null && endDate.length() > 0){
	    				eDate = sdf.parse(endDate);
	    	    	}
	    		}
	    		OutputStream out = response.getOutputStream();
	    		response.resetBuffer();
				response.setContentType("aplication/vnd.ms-excel");
				response.setHeader("Content-disposition", "attachment;filename=my_order.xlsx");
				OutputStream os = response.getOutputStream();
	    		orderService.exportMobileOrderByMobileAndCreatedDate(mobileUser.getMobile(), sDate, eDate, out);
	    	} catch (ParseException e1) {
				e1.printStackTrace();
			} catch (IOException e2) {
				e2.printStackTrace();
			}  catch (Exception e3) {
				e3.printStackTrace();
			} 
    	}
    }
    
    //mobile functions
    @RequestMapping(value = "/mobile/order_send_sms", method = RequestMethod.POST)
    @ResponseBody
    public ResultDto doOrderQuerySendSMS(String mobile) throws Exception {
    	try{
    		orderService.sendValidationCode(mobile);
    	}catch(Exception ex){
    		return ResultDtoFactory.toAck("errorMsg",ex.getMessage());
    	}
        
        return ResultDtoFactory.toAck("短信验证码发送成功");
    }
    
    @RequestMapping(value = "/mobile/find-order")
    public String toOrderQuery(Model model){
        return "order/mobile_find_order";
    }
    
    @RequestMapping(value = "/mobile/find-order/orderList")
    public String orderQuery(Model model, String mobile, String code){
    	try{
    		model.addAttribute("mobile", mobile);
    		orderService.validateCode(mobile, code);
    		model.addAttribute("orders", orderService.findByReceiverPhoneAndOrderDate(mobile, null, null));
    	}catch(Exception ex){
    		model.addAttribute("errorMsg", ex.getMessage());
    	}
    	return "order/mobile_foundOrders";
    }
    
    @RequestMapping(value = "/mobile/myOrders")
    public String recentOrders(HttpSession session, Model model){
    	try{
    		MobileUser mobileUser=(MobileUser)session.getAttribute("mobileUser");
    		model.addAttribute("gotoURL", "mobile/myOrders");
    		if(mobileUser==null){
    			return "mobile_login";
    		}
    		String mobile = mobileUser.getMobile();
    		Calendar c = Calendar.getInstance();
    		Date endDate = c.getTime();
    		c.add(Calendar.DAY_OF_MONTH, -10);
    		c.set(Calendar.HOUR_OF_DAY, 0);
    		c.set(Calendar.MINUTE, 0);
    		c.set(Calendar.SECOND, 0);
    		c.set(Calendar.MILLISECOND, 0);
    		Date startDate = c.getTime();
    		List<MobileOrder> orders = orderService.findMobileOrderByMobileAndCreatedDate(mobile, startDate, endDate);
    		model.addAttribute("orders", orders);
    		model.addAttribute("ordersJson", JsonUtil.toJSon(orders));
    	}catch(Exception ex){
    		model.addAttribute("errorMsg", "查询订单异常！");
    	}
    	return "order/mobile_orders";
    }
    
    @RequestMapping(value = "/mobile/findOrders")
    @ResponseBody
    public ResultDto findOrders(HttpSession session, String startDate, String endDate){
    	MobileUser mobileUser=(MobileUser)session.getAttribute("mobileUser");
		if(mobileUser==null){
			return ResultDtoFactory.toAck("errorMsg", "会话过期");
		}
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    	Date sDate=null;
    	Date eDate=null;
    	try {
    		if((startDate==null  || startDate.length()==0)&& (endDate==null || endDate.length()==0)){
    			eDate=new Date();
    			Calendar c = Calendar.getInstance();
	    		c.add(Calendar.DAY_OF_MONTH, -10);
	    		c.set(Calendar.HOUR_OF_DAY, 0);
	    		c.set(Calendar.MINUTE, 0);
	    		c.set(Calendar.SECOND, 0);
	    		c.set(Calendar.MILLISECOND, 0);
	    		sDate=c.getTime();
    		}else{
    			if(startDate != null && startDate.length() > 0){
    				sDate = sdf.parse(startDate);
    	    	}
    			if(endDate != null && endDate.length() > 0){
    				eDate = sdf.parse(endDate);
    	    	}
    		}
    		
    		return ResultDtoFactory.toAck("successMsg", orderService.findMobileOrderByMobileAndCreatedDate(mobileUser.getMobile(), sDate, eDate));
    	} catch (ParseException e) {
			e.printStackTrace();
			return ResultDtoFactory.toAck("errorMsg", "日期转换异常！");
		} catch (Exception e) {
			e.printStackTrace();
			return ResultDtoFactory.toAck("errorMsg", "会话过期");
		}
    }
    
    @RequestMapping(value = "/mobile/selection/orderEntry")
	public String orderEntry(HttpSession session, Model model, String productCode, Long modelId, String category) throws UnsupportedEncodingException{
    	MobileUser mobileUser=(MobileUser)session.getAttribute("mobileUser");
    	model.addAttribute("gotoURL", "mobile/selection/orderEntry?productCode="+productCode+"&modelId="+modelId+"&category="+category);
		if(mobileUser==null){
			return "mobile_login";
		}
		model.addAttribute("model", vehicleService.findVehicleModelById(modelId));
		model.addAttribute("category", category);
		productCode = URLDecoder.decode(productCode,"UTF-8");
		model.addAttribute("carTypeCode", productCode);
		return "order/mobile_orderEntry";
	}
	
	@RequestMapping(value = "/mobile/submitOrder")
	@ResponseBody
	public ResultDto submitOrder(HttpSession session, MobileOrder order, String footAppend, String tailAppend){
		MobileUser mobileUser=(MobileUser)session.getAttribute("mobileUser");
		if(mobileUser==null){
			return ResultDtoFactory.toAck("errorMsg", "会话过期");
		}
		order.setCreatedAt(new Date());
		order.setCreatedBy(mobileUser.getMobile());
		orderService.saveMobileOrder(order,footAppend, tailAppend);
		return ResultDtoFactory.toAck("successMsg", order);
	}
}
